package org.example.samplebusiness.service;

import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.example.api.*;
import org.example.dto.AccountDto;
import org.example.dto.OrderDto;
import org.example.dto.RepoDto;
import org.example.exception.BizException;
import org.example.response.R;
import org.springframework.stereotype.Service;

/**
 * @author Kong
 * @date 2021-9-13 16:52
 */
@Slf4j
@Service
public class BusinessService {
    @DubboReference
    private OrderApi orderApi;
    @DubboReference
    private RepoApi repoApi;
    @DubboReference(timeout = 5000)
    private AccountApi accountApi;
    @DubboReference
    private OrderApiTcc orderApiTcc;
    @DubboReference
    private RepoApiTcc repoApiTcc;
    @DubboReference
    private AccountApiTcc accountApiTcc;
    @GlobalTransactional(timeoutMills = 30000,name = "spring-cloud-seata-at")
    public R createOrderAT(OrderDto orderDto) {
        log.info("[AT模式]开启全局事务XID：{}" , RootContext.getXID());
        AccountDto accountDto = new AccountDto();
        accountDto.setUserId(1);
        accountDto.setBalance(orderDto.getAmount());
        accountApi.decrease(accountDto);
        orderApi.createOrder(orderDto);
        RepoDto repoDto = new RepoDto();
        repoDto.setProductCode(orderDto.getProductCode());
        repoDto.setAccount(orderDto.getCount());
        repoApi.decreaseRepo(repoDto);
        //return R.Builder.getInstance().buildOk().build();
        throw new BizException();
    }

    @GlobalTransactional(timeoutMills = 30000,name = "spring-cloud-seata-tcc")
    public R createOrderTCC(OrderDto orderDto) {
        log.info("[TCC模式]开启全局事务XID：{}" , RootContext.getXID());
        AccountDto accountDto = new AccountDto();
        accountDto.setUserId(1);
        accountDto.setBalance(orderDto.getAmount());
        accountApiTcc.decrease(accountDto);
        RepoDto repoDto = new RepoDto();
        repoDto.setProductCode(orderDto.getProductCode());
        repoDto.setAccount(orderDto.getCount());
        repoApiTcc.decreaseRepo(repoDto);
        orderApiTcc.createOrder(orderDto);
        return R.Builder.getInstance().buildOk().build();
        //throw new BizException();
    }
}
